package J20241026_HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description: 哈希map实现
 * User: 王圆豪
 * Date: 2024-10-26
 * Time: 21:59
 */
public class HashBuck {
    static class Node{
        private int key;
        private int val;
        private Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node[] array = new Node[10];
    private int usedSize;
    private static final double LOAD_FACTOR = 0.75;

    public void push(int key, int val){
        if (usedSize * 1.0 / array.length >= LOAD_FACTOR){
            expansion();
        }

        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        cur = new Node(key, val);

        //头插
        cur.next = array[index];
        array[index] = cur;
        usedSize++;
    }

    //扩容
    private void expansion() {
        Node[] newArray = new Node[2 * array.length];
        for (Node n:
             array) {
            while (n != null){
                int newIndex = n.key % newArray.length;

                Node nt = n.next;
                n.next = newArray[newIndex];
                newArray[newIndex] = n;

                n = nt;
            }
        }
        array = newArray;
    }

    //根据key获得val
    public int getVal(int k){
        int h = k % array.length;
        Node n = array[h];
        while (n != null){
            if (n.key == k){
                return n.val;
            }
            n = n.next;
        }
        return -1;
    }
}
